package com.example.demo2.config;

import com.example.demo2.interceptor.loginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

import java.io.File;

@Configuration
public class WebConfig  implements WebMvcConfigurer {

    // 获取当前工作目录的File对象
    File userDir = new File(System.getProperty("user.dir"));

    // 获取父目录的File对象，即D:/idea/
    File parentDir = userDir.getParentFile();

    // 再次获取上一级目录的File对象，即D:/
    File grandParentDir = parentDir.getParentFile();

    // 现在grandParentDir指向D:/，我们想在D:/下创建file目录
    // 因此，我们创建一个新的File对象指向D:/file
    File fileDir = new File(grandParentDir, "file");

    // 将fileDir转换为绝对路径
    String ROOT_PATH = fileDir.getAbsolutePath();

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new loginInterceptor());
    }

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080","http://localhost:9528")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/files/**")
                .addResourceLocations("file:/" + ROOT_PATH + "/");
    }

}
